from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
import requests
import urlparse


def parse_http_request(req_text, scheme="http"):
    class HTTPRequest(BaseHTTPRequestHandler):
        def __init__(self, request_text):
            # request_text = '\n'.join([line for line in req_text.split() if line.strip()])
            self.rfile = StringIO(request_text)
            self.raw_requestline = self.rfile.readline()
            self.error_code = self.error_message = None
            self.parse_request()

        def send_error(self, code, message):
            self.error_code = code
            self.error_message = message
            
    http_request = HTTPRequest(req_text)
    # print http_request
    print http_request.command
    method = http_request.command.lower()

    if not hasattr(requests, method):
        raise RuntimeError("Cannot find HTTP method %s" % method)

    req = requests.Request(
        method=method,
        url=urlparse.urljoin(scheme+"://" + http_request.headers['host'], http_request.path),
        headers= http_request.headers,
        # http_request.headers.getheader('content-length', 0)
        data=http_request.rfile.read()
    )

    return req

if __name__=="__main__":
    import sys
    s = """POST "/api/v1/bannerControl" HTTP/1.1
Host: fcms.bestpay.com.cn
Content-Length: 90
Accept: application/json, text/javascript, */*; q=0.01
Origin: file://
User-Agent: Mozilla/5.0 (Linux; Android 4.4.4; Coolpad 8675-A Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 Bestpay/5.2.4
Content-Type: application/json;charset=UTF-8
Accept-Encoding: gzip,deflate
Accept-Language: zh-CN,en-US;q=0.8
X-Requested-With: com.chinatelecom.bestpayclient

asd"""

    a= parse_http_request(s)
    print a.data